package com.haotunet.app.goldtreasure.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.PopupWindow;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.utils.TextUtils;
import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.net.UrlUtil;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.TagUtils;
import com.haotunet.app.goldtreasure.views.SharePopupView;
import com.haotunet.app.goldtreasure.views.TitleView;
import com.umeng.socialize.utils.Log;

import java.util.HashMap;
import java.util.Map;

@Route(path = "/mine/invite")

public class DynamicDetailActivity extends BaseActivity {
    @Autowired
    String inviteUrl;
    @Autowired
    String pushUrl;
    private View mRootView;
    private WebView mWebView;
    private FrameLayout mVideoContainerFrameLayout;
    private WebChromeClient.CustomViewCallback mCallBack;
    private TitleView mtTitleView;
    private String mUrl;
    private String mTitle;
    private String mContent;
    private String mImageUrl;
    private ShareStore shareStore;
    private int type;
    private String activityUrl;
    private String mCurrentUrl;
    private Map<String, String> mTitlesMap = new HashMap<>();
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case 0:
                    showSharePopup();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_detail);
        shareStore = new ShareStore(this);
        initView();

    }

    @SuppressWarnings({"deprecation"})
    private void initView() {
        if (getIntent().hasExtra("activityUrl")) {
            activityUrl = getIntent().getStringExtra("activityUrl");
        }
        if (getIntent().hasExtra("inviteUrl")) {
            activityUrl = UrlUtil.INVITE_URL;
        }
        if (getIntent().hasExtra("pushUrl")) {
            activityUrl = getIntent().getStringExtra("pushUrl");
        }
        activityUrl = Uri.parse(activityUrl).buildUpon().appendQueryParameter("platform", "android").build().toString();
        type = getIntent().getIntExtra("type", 0);
        mRootView = findViewById(R.id.root);
        mtTitleView = (TitleView) findViewById(R.id.title_view_dynamic);
        mtTitleView.getTitletextView().setVisibility(View.VISIBLE);
        if (type == 10 || type == 11 /*|| type == 12*/) {

            mtTitleView.getRightText().setVisibility(View.VISIBLE);
            mtTitleView.getRightText().setText(getString(R.string.share));
            mtTitleView.getRightText().setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    showSharePopup();
                }
            });
        }
        mtTitleView.getBackView().setVisibility(View.VISIBLE);
        mtTitleView.getBackView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    if (type == 0) {
                        setResult(RESULT_OK);
                    }
                    finish();
                }
            }
        });
        mVideoContainerFrameLayout = (FrameLayout) findViewById(R.id.videoContainer);
        mWebView = (WebView) findViewById(R.id.webview_dynamic);
        setCookie();
        mWebView.getSettings().setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.addJavascriptInterface(new JsOperation(this), "android");
        Map<String, String> extraHeaders = new HashMap<>();
        extraHeaders.put("Referer", "api.goldplusgold.com");


        mWebView.getSettings().setDomStorageEnabled(true);//DOM Storage
        //mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
        //mWebView.getSettings().setJavaScriptEnabled(true);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        //mWebView.getSettings().setSupportZoom(true);//是否可以缩放，默认true
        //mWebView.getSettings().setBuiltInZoomControls(true);//是否显示缩放按钮，默认false
        //mWebView.getSettings().setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
        //mWebView.getSettings().setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        //mWebView.getSettings().setAppCacheEnabled(true);//是否使用缓存
        //displayWebview.getSettings().setUserAgentString("User-Agent:Android");//设置用户代理，一般不用


        mWebView.loadUrl(activityUrl, extraHeaders);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return false;
                }
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                mCurrentUrl = url;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String title = mTitlesMap.get(url);
                if (!TextUtils.isEmpty(title)) {
                    mtTitleView.getTitletextView().setText(title);
                }
                String js = TagUtils.getJs(url);
                view.loadUrl(js);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                setProgress(newProgress * 100);
                if (newProgress == 100) {
                    mWebView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (TextUtils.isEmpty(title)) {
                    title = "";
                }
                mTitlesMap.put(mCurrentUrl, title);
                mtTitleView.getTitletextView().setText(title);
            }


            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                fullScreen();
                mWebView.setVisibility(View.GONE);
                mVideoContainerFrameLayout.setVisibility(View.VISIBLE);
                mVideoContainerFrameLayout.addView(view);
                mCallBack = callback;
                super.onShowCustomView(view, callback);
            }

            @Override
            public void onHideCustomView() {
                fullScreen();
                if (mCallBack != null) {
                    mCallBack.onCustomViewHidden();
                }
                mWebView.setVisibility(View.VISIBLE);
                mVideoContainerFrameLayout.removeAllViews();
                mVideoContainerFrameLayout.setVisibility(View.GONE);
                super.onHideCustomView();

            }
        });

    }

    private void showSharePopup() {
        SharePopupView sharePopupView = new SharePopupView(DynamicDetailActivity.this,
                DynamicDetailActivity.this, mUrl, mTitle, mContent, mImageUrl);
        sharePopupView.showAtLocation(mRootView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        ActivityUtils.backgroundAlpha(DynamicDetailActivity.this, 0.5f);
        sharePopupView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ActivityUtils.backgroundAlpha(DynamicDetailActivity.this, 1f);
            }
        });
    }

    public class JsOperation {
        Context context;

        public JsOperation(Context c) {
            context = c;
        }

        @JavascriptInterface
        public void fullscreen() {
            //监听到用户点击全屏按钮
            fullScreen();
        }

        @JavascriptInterface
        public void makeOrder(int switchTab, String productId, String productName, int productType) {
            boolean isLogin = shareStore.getBoolean(Strs.IS_LOGIN, false);
            if (isLogin) {
                ActivityUtils.gotoBuyGold(context, 2, productName, productId, switchTab, productType);
            } else {
                gotoLogin();
            }
        }

        @JavascriptInterface
        public void appLogin() {
            gotoLogin();
        }

        @JavascriptInterface
        public void currentToFixedPeriod(String productId, String productName) {
            boolean isLogin = shareStore.getBoolean(Strs.IS_LOGIN, false);
            if (isLogin) {
                ActivityUtils.gotoCurrentTransfer(context, productId, productName);
            } else {
                ActivityUtils.gotoLogin(context);
            }
        }

        @JavascriptInterface
        public void share(String title, String content, String imageUrl, String url) {
            mTitle = title;
            mContent = content;
            mImageUrl = imageUrl;
            mUrl = url;
            Log.i("title=" + mTitle + ",content=" + mContent + ",imageUrl=" + mImageUrl + ",url=" + mUrl);
        }

        @JavascriptInterface
        public void inviteFriendsShare(String title, String content, String imageUrl, String url) {
            mTitle = title;
            mContent = content;
            mImageUrl = imageUrl;
            mUrl = url;
            Message msg = new Message();
            msg.what = 0;
            mHandler.sendMessage(msg);
        }
    }

    private void gotoLogin() {
        Intent intent = new Intent(DynamicDetailActivity.this, LoginActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        } else {
            if (type == 0) {
                setResult(RESULT_OK);
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (type == 12) {
            mWebView.reload();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            setCookie();
            mWebView.reload();
        }
    }

    private void setCookie() {
        CookieSyncManager.createInstance(DynamicDetailActivity.this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();
        cookieManager.setCookie(activityUrl, "_x-access-token=" + shareStore.getString(Strs.TOKEN, "")); // 你想设置的参数
        cookieManager.setCookie(activityUrl, "_version=" + shareStore.getString("versionName", "")); // 你想设置的参数
        cookieManager.setCookie(activityUrl, "_platform=android"); // 你想设置的参数
        CookieSyncManager.getInstance().sync();
    }

    private void fullScreen() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

}
